package com.wine.exam.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Pattern;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wine.common.annotation.RepeatSubmit;
import com.wine.exam.domain.Paper;
import com.wine.exam.domain.PaperQuestion;
import com.wine.exam.dto.PaperDto;
import com.wine.exam.service.IPaperQuestionService;
import com.wine.exam.service.IPaperService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wine.common.annotation.Log;
import com.wine.common.core.controller.BaseController;
import com.wine.common.core.domain.AjaxResult;
import com.wine.common.enums.BusinessType;

import com.wine.common.utils.poi.ExcelUtil;
import com.wine.common.core.page.TableDataInfo;

/**
 * 试卷Controller
 *
 * @author wine
 * @date 2022-10-13
 */
@RestController
@RequestMapping("/exam/paper")
public class PaperController extends BaseController {
    @Autowired
    private IPaperService iPaperService;
    @Autowired
    private IPaperQuestionService iPaperQuestionService;


    /**
     * 根据试卷名称，学科，开始，结束时间 可选查询 试卷
     *
     * @param paperDto
     * @return
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:paper:index')")
    @GetMapping("/list")
    public AjaxResult list(PaperDto paperDto) {

        Page<Paper> page = iPaperService.pageQueryList(paperDto);
        return AjaxResult.success(page);

    }

    /*
       /**
        * 导出试卷列表 ：由于试卷特殊行，不支持导入导出。其实也简单，后期再看吧
        */
 /*   @PreAuthorize("@ss.hasPermi('exam:paper:export')")
    @Log(title = "试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Paper paper) {
        List<Paper> list = iPaperService.selectPaperList(paper);
        ExcelUtil<Paper> util = new ExcelUtil<Paper>(Paper.class);
        util.exportExcel(response, list, "试卷数据");
    }*/

    /*
     * 获取试卷详细信息 : 含有答案
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:paper:detail')")
    @GetMapping(value = "/{paperId}")
    public AjaxResult getInfo(@PathVariable("paperId") Long paperId) {
        Map<String, Object> info = iPaperService.getInfo(paperId, true);
        return AjaxResult.success(info);
    }

    /*
     * 获取试卷详细信息 : 无答案
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:paper:doexam')")
    @GetMapping(value = "/doexam/{paperId}")
    public AjaxResult getInfoNoCorrect(@PathVariable("paperId") Long paperId) {
        Map<String, Object> info = iPaperService.getInfo(paperId, false);
        return AjaxResult.success(info);
    }

    /*
     * 提交试卷
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:paper:doexam')")
    @PostMapping(value = "/submit/{paperId}")
    public AjaxResult submit(@PathVariable("paperId") Long paperId) {
        Map<String, Object> info = iPaperService.getInfo(paperId,true);
        return AjaxResult.success(info);
    }


    /**
     * 新增试卷  看了下mp官方：说是批量操作controller层。。。。 暂时测试也正常
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:paper:add')")
    @Log(title = "试卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Paper paper) {
        paper.setCreateBy(this.getUserId().toString());
        paper.setUpdateBy(this.getUserId().toString());
        iPaperService.save(paper);


        if (paper.getQuestionIds().length > 0) {
//            选了题在操作

            ArrayList<PaperQuestion> paperQuestions = new ArrayList<>();
            for (String s : paper.getQuestionIds()) {
                PaperQuestion paperQuestion = new PaperQuestion();
                //  获取自增id
                paperQuestion.setPaperId(paper.getPaperId());

                paperQuestion.setQuestionId(Long.parseLong(s));
                paperQuestions.add(paperQuestion);
            }
            iPaperQuestionService.saveBatch(paperQuestions);
        }


        return AjaxResult.success("新增试卷成功");
    }


    /**
     * 删除试卷
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:paper:remove')")
    @Log(title = "试卷", businessType = BusinessType.DELETE)
    @DeleteMapping("/{paperId}")
    public AjaxResult remove(@PathVariable Long paperId) {
        System.out.println("paperId" + paperId);
        int row = iPaperService.delById(paperId);
        return toAjax(row);

    }


    /**
     * 修改 设置status
     */
    @RepeatSubmit(interval = 10000 ,message = "不允许重复提交，请稍候再试")
    @PreAuthorize("@ss.hasPermi('exam:subject:edit')")
    @Log(title = "问题状态", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus/{paperId}/{status}")
    public AjaxResult editStatus(@PathVariable Long paperId,
                                 @Pattern(regexp = "[0,1]", message = "问题状态:0=正常,1=停用")
                                 @PathVariable String status) {
        return toAjax(
                iPaperService.updateStatus(paperId, status)
        );
    }

}
